<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaServer Pages, (JSPs)</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, java, web applications, JSP">
<meta name="description" content="This part of the Java EE 5 tutorials covers Java Server Pages, (JSPs).">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>JavaServer Pages, (JSPs)</h1>


<p>
In this part of the Java EE 5 tutorials, we will work with JavaServer Pages (JSPs).
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
JavaServer Pages is a technology, that enables to create HTML dynamically. 
JSPs are compiled into servlets by a JSP compiler.
A JSP page is a text-based document. It can contain two types of text: static 
data and JSP elements, which determine how the page constructs dynamic content.
</p>

<p>
JavaServer pages is an integral part of the Java EE platform. Huge enterprise 
applications are layered. The JSP pages represent the presentation layer of the 
application. In the MVC (Model, View, Controller) pattern, this is the
View part. The data is processed by the business logic of the application.
The model loads the data from the 
database. The data is sent by the controller to the appropriate JSP page for displaying. 
</p>

<p>
The JavaServer Pages consists of several key features:
</p>

<ul>
<li>Scripting elements</li>
<li>Standard directives</li>
<li>Standard actions</li>
<li>Tag extensions</li>
</ul>

<p>
JSP pages go through two phases. Translation phase and execution phase. 
The JSP page is translated once per page. 
The JSP page is executed once per request. Internally, the JSP page is 
transformed into servlet, which is then compiled. 
</p>

<p>
The JSP pages have a .jsp extension.
</p>

<!--WAR file (short for Web ARchive) could be a JAR file used to distribute a collection of 
JavaServer Pages, servlets, Java classes, XML files, tag libraries and static Web pages 
(HTML and related files) that together constitute a Web application.
-->


<h2>Scripting elements</h2>

<p>
We have <b>declarations</b>, <b>expressions</b> and <b class="keyword">scriptlets</b>. 
Scripting elements are used to manipulate objects and perform calculations. Scripting in done 
in the Java language. Each of them is put inside specific tags.
</p>

<pre class="code">
&lt;%! declaration %&gt;
&lt;% scriptlet %&gt;
&lt;%= expression %&gt;
</pre>

<p>
<b>Declaration</b> is used to declare variables and methods in a JSP page. 
<b>Scriptlet</b> is a piece of Java code. It performs some dynamic action 
within a JSP page. It can manipulate objects or print some text or html data.
<b>Expression</b> outputs data, which is displayed in a browser. 


<h3>Celsius to Fahrenheit</h3>

<p>
In the following example, we use all three elements. We will convert 
Celsius temperature to Fahrenheit.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;


&lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;Fahrenheit&lt;/title&gt;
      &lt;style&gt;
          * { font-size: 12px; font-family: Verdana }
      &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;h2&gt;Fahrenheit&lt;/h2&gt;

      &lt;%!
        double fahr1, fahr2, fahr3;
        int cels1 = 20;
        int cels2 = 36;
        int cels3 = 45;

        double calculate(int cels) {
            return cels * 9 / 5.0 + 32;
        }
      %&gt;

      &lt;%
        fahr1 = calculate(cels1);
        fahr2 = calculate(cels2);
        fahr3 = calculate(cels3);
      %&gt;

      &lt;p&gt;
       &lt;%= cels1 %&gt; Celsius is &lt;%= fahr1 %&gt; Fahrenheit&lt;br&gt;
       &lt;%= cels2 %&gt; Celsius is &lt;%= fahr2 %&gt; Fahrenheit&lt;br&gt;
       &lt;%= cels3 %&gt; Celsius is &lt;%= fahr3 %&gt; Fahrenheit&lt;br&gt;
      &lt;/p&gt;

  &lt;/body&gt;
&lt;/html>
</pre>


<pre class="explanation">
&lt;%!
  double fahr1, fahr2, fahr3;
  int cels1 = 20;
  int cels2 = 36;
  int cels3 = 45;

  double calculate(int cels) {
      return cels * 9 / 5.0 + 32;
  }
%&gt;
</pre>

<p>
In this declaration, we declare six variables and one function.
</p>


<pre class="explanation">
&lt;%
  fahr1 = calculate(cels1);
  fahr2 = calculate(cels2);
  fahr3 = calculate(cels3);
%&gt;
</pre>

<p>
In the scriptlet, we perform the computation. 
</p>


<pre class="explanation">
&lt;p&gt;
 &lt;%= cels1 %&gt; Celsius is &lt;%= fahr1 %&gt; Fahrenheit&lt;br&gt;
 &lt;%= cels2 %&gt; Celsius is &lt;%= fahr2 %&gt; Fahrenheit&lt;br&gt;
 &lt;%= cels3 %&gt; Celsius is &lt;%= fahr3 %&gt; Fahrenheit&lt;br&gt;
&lt;/p&gt;
</pre>

<p>
In the expression, we output the variables. 
</p>

<img src="/img/java/jee/fahrenheit.png" alt="Celsius to Fahrenheit">
<div class="figure">Figure: Celsius to Fahrenheit</div>



<h2>From JSP to a servlet</h2>

<p>
Next we will show, how a container transforms a JSP page to a servlet.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;style&gt;
            * { font-size: 12px; font-family: Verdana }    
        &lt;/style&gt;
        &lt;title&gt;SimpleJSP&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;

        &lt;%= "Simple JSP page" %&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
We will have this simple JSP page. All it does is print some text. We will look, 
how a container transforms the page into a servlet. 
</p>


<div class="codehead">index_jsp.java</div>
<pre class="code">
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends 
                   org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = 
                   JspFactory.getDefaultFactory();

  private static java.util.Vector _jspx_dependants;

  private org.apache.jasper.runtime.ResourceInjector 
                   _jspx_resourceInjector;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, 
               HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=UTF-8");
      response.setHeader("X-Powered-By", "JSP/2.1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector)
         application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write("\n");
      out.write("\n");
      out.write("&lt;html&gt;\n");
      out.write("  &lt;head&gt;\n");
      out.write("      &lt;style&gt;\n");
      out.write("       * { font-size: 12px; font-family: Verdana } \n");
      out.write("      &lt;/style&gt;\n");
      out.write("      &lt;title&gt;SimpleJSP&lt;/title&gt;\n");
      out.write("  &lt;/head&gt;\n");
      out.write("  &lt;body&gt;\n");
      out.write("      \n");
      out.write("        ");
      out.print( "Simple JSP page" );
      out.write("\n");
      out.write("      \n");
      out.write("  &lt;/body&gt;\n");
      out.write("&lt;/html&gt;\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null &amp;&amp; out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) 
            _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
</pre>

<p>
This is the code generated by the Glassfish. Note that different containers 
will generate different code. 
To see the servlet code in Netbeans IDE, we run the application first. Then 
we right click on the jsp page in the Projects window and select option View Servlet.  
</p>

<img src="/img/java/jee/genservlet.png" alt="View Servlet">
<div class="figure">Figure: View Servlet</div>



<h2>Directives</h2>

<p>
Directives are messages to the JSP container. There are three main directives.
</p>

<ul>
<li>page</li>
<li>include</li>
<li>taglib</li>
</ul>


<p>
The <b>page</b> directive defines several properties for a JSP page.
</p>
<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;style&gt;
      * { font-size: 12px; font-family: Verdana }
    &lt;/style&gt;
    &lt;title&gt;Партизанская&lt;/title&gt;
  &lt;/head&gt;

 &lt;body&gt;
 &lt;h3&gt;По долинам и по взгорьям&lt;/h3&gt;
 &lt;pre&gt;
   По долинам и по взгорьям
Шла дивизия вперед,
Чтобы с бою взять Приморье -
Белой армии оплот.

Наливалися знамена
кумачом последних ран,
Шли лихие эскадроны
Приамурских партизан.

Этих лет не смолкнет слава,
Не померкнет никогда,
Партизанские отряды
Занимали города.

И останутся как в сказке,
Как манящие огни,
Штурмовые ночи Спасска,
Волочаевские дни.

Разгромили атаманов,
Разогнали воевод,
И на Тихом океане
Свой закончили поход. 
 &lt;/pre&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
The example illustrates the <b class="keyword">pageEncoding</b> attribute of the page directive.
We display text of a song in russian language.
</p>

<pre class="explanation">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
</pre>

<p>
The directive sets the encoding to UTF-8. It covers also the russian 
language. If we would not set this encoding, the JSP page would use the 
default ISO-8859-1 encoding. The page would not display the text correctly.
</p>

<img src="/img/java/jee/partisanskaja.png" alt="Партизанская">
<div class="figure">Figure: Партизанская</div>


<p>
The <b>contentType</b> attribute defines the MIME type. 
It tells the browser, how to interprete the
data. The default contentType is text/html. In this case, the client 
browser interpretes all the html code. The 
&lt;br&gt; is a new line, &lt;p&gt;&lt;/p&gt; a paragraph etc.  
</p>


<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/plain" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;style&gt;
            * { font-size: 12px; font-family: Verdana }    
        &lt;/style&gt;
        &lt;title&gt;ContentType&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;

       &lt;b&gt;Plain text content type&lt;/b&gt;

    &lt;/body&gt;
&lt;/html>
</pre>

<p>
If we set the contentType to text/plain, we tell the browser to interprete 
all textual data as simple text. 
So the html tags are not interpreted and are simply displayed.
</p>


<img src="/img/java/jee/plain.png" alt="Plain text">
<div class="figure">Figure: Plain text</div>


<h3>Error page</h3>

<p>
We can use the <b>errorPage</b> attribute to handle exceptions 
in the JSP page. 
</p>


<pre class="code">
<div class="codehead">index.jsp</div>
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@page errorPage="errorPage.jsp" %&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;JSP Page&lt;/title&gt;
    &lt;/head&gt;

    &lt;body&gt;
        &lt;%
            int num = 77 / 0;  
        %&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
An exception occurs in this JSP page. Our exception will raise, when we try to divide by zero.
</p>


<pre class="explanation">
&lt;%@page errorPage="errorPage.jsp" %&gt;
</pre>

<p>
With the <b>errorPage</b> attribure, we tell the container to show 
the errorPage.jsp, if there is some exception.
</p>

<div class="codehead">errorPage.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@page isErrorPage="true" %&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Error occured&lt;/title&gt;
        &lt;style&gt;
            * { font-size: 12px; font-family: Verdana }    
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h2&gt;Error&lt;/h2&gt;

        &lt;%= exception.getMessage() %&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
Here we process the exception. 
</p>

<pre class="explanation">
 &lt;%@page isErrorPage="true" %&gt;
</pre>

<p>
With the <b>isErrorPage</b> attribute, we make the 
<b class="keyword">exception</b> object available to this JSP page. 
</p>

<pre class="explanation">
&lt;%= exception.getMessage() %&gt;
</pre>

<p>
We display the error message.
</p>

<img src="/img/java/jee/errorpage.png" alt="Error page">
<div class="figure">Figure: Error page</div>


<p>
If we do not provide an error page, we get an error message from the container.
</p>

<img src="/img/java/jee/error500.png" alt="Error 500">
<div class="figure">Figure: Error 500</div>



<p>
The <b>include</b> directive enables us to organize the code 
effectively. All websites have repeating code. An example is
the common copyright notice or navigation menu. If the website grows larger, 
it gets time consuming to correct the code in all files. When the year changes, 
we should change the copyright notice in all files. This is not possible with simple html. 
</p>

<div class="codehead">style.css</div>
<pre class="code">
.left {
    position: absolute;
    left:10px;
    top:55px;
    width:200px; height:200px;
    border:1px solid #4B8699;
}

.center {
    position: relative;
    top:1px;
    margin-left: 210px;
    margin-right:210px;
    border:1px solid #4B8699;
    height:200px;
}

.right {
    position: absolute;
    right:10px;
    top:55px;
    width:200px; height:200px;
    border:1px solid #4B8699;
}


.banner {
  border:1px solid #4B8699;
  height:44px;
}

.footer {
  margin-top:3px;
  border: 1px solid #4B8699;
  height:35px;
  text-align:center;
  padding-top:9px;
}

* { font-size: 12px; font-family: Verdana }
</pre>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Include&lt;/title&gt;
        &lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
    &lt;/head&gt;
    &lt;body&gt;

      &lt;div class="banner"&gt;
      &lt;/div&gt;

      &lt;div class="left"&gt;
      &lt;/div&gt;

      &lt;div class="center"&gt;
      &lt;/div&gt;

      &lt;div class="right"&gt;
      &lt;/div&gt;

      &lt;div class="footer"&gt;
          &lt;%@ include file="WEB-INF/jspf/footer.jspf" %&gt;
      &lt;/div&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
We divide our page into five parts. We use include directive to 
include the copyright notice into the footer.
</p>

<pre class="explanation">
&lt;%@ include file="WEB-INF/jspf/footer.jspf" %&gt;
</pre>

<p>
Here we include the footer. The included code fragments have a <b>.jspf</b> ending.  
</p>


<div class="codehead">footer.jspf</div>
<pre class="code">
&lt;%@ page pageEncoding="UTF-8" %&gt;

&lt;div&gt;&lt;b&gt;ZetCode&lt;/b&gt; @ 2007 - 2008 Jan Bodnar&lt;/div&gt;
</pre>

<p>
If we use include files, we need to update the text only once. 
</p>


<img src="/img/java/jee/include.png" alt="Including footer">
<div class="figure">Figure: Including footer</div>


<p>
The <b>taglib</b> directive defines a tag library and 
prefix for the custom tags used in the JSP page.
We will use this directive later in our Java EE 5 tutorials. When we 
will work with custom JSP tags.
</p>


<h2>Deploying a web application</h2>

<p>
We will deploy our first web application, using the Resin application server.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Date&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;p&gt;
Date: <%= new java.util.Date() %>
&lt;/p&gt;

&lt;/body>
&lt;/html>
</pre>

<p>
The simple jsp file consists of html code and java code. Here we use a jsp 
expression, which will output the current date.
</p>

<pre class="code">
$ ls
index.jsp
</pre>

<p>
In our working directory, we have only one file named index.jsp. And now,
we need to deploy it to the server. 
</p>

<p>
Deployment of web applications is similar to installing classical programs 
on desktop. These are steps needed
to run the web application. 
</p>

<p>
In Java EE a web application is called a <b>web module</b>. It is the simplest 
deployable unit.  
</p>

<pre class="code">
$ ./httpd.sh start
Resin/3.1.3 started -server ''.
</pre>

<p>
First, we start the Resin server. The <b>httpd.sh</b> script is located in the 
bin directory.
</p>


<pre class="code">
$ jar -cvf date.war *
added manifest
adding: index.jsp(in = 110) (out= 85)(deflated 22%)
</pre>

<p>
We create a <b>web archive</b>.
</p>

<pre class="code">
$ ls
date.war  index.jsp
</pre>

<p>
We have created a war file. 
</p>

<pre class="code">
$ mv date.war /home/vronskij/bin/resin/webapps/
</pre>

<p>
We move the war file to the Resin AS <b>webapps</b> subdirectory. Here you 
must provide your own path to the directory depending on where you have 
installed the Resin server. By moving the war file to the webapps directory, 
the application is deployed and we can test it. Note that it is possible 
to deploy a web application, while the server
is running.
</p>

<p>
Our JSP file displays current date. We write http://localhost:8080/date/ to 
our web browser to test the outcome. The localhost:8080 means, that we test our application on our 
local machine and the Resin server listens on 8080 port. The date path is 
called the <b>context path</b>. It is the context root or path to our application.
We can have several applications deployed at one time. The context path can be 
specified in configuration files. When it is not, than it is equal to the war file name. 
</p>


<img src="/img/java/jee/date.png" alt="Date">
<div class="figure">Figure: Date</div>


<p>
In this chapter, we have covered Java Server Pages.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 8, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

